<?php
try{
	include '../ini.php';
    include '../classes/xl_posts.php';
    $dt_xl_post=new xl_posts;
    if(empty($_GET['id'])){
        throw new Exception('Không tồn tại mã này');
    }
   
    $read_post=$dt_xl_post->read($_GET['id']);
    if($_GET['id'] != $read_post['id']){
        $_GET['id']=$dt_xl_admin->removeSQLI($_GET['id']);
        header("Location: posts_update.php?id=".$_GET['id']);
    }
    if($read_post === false){
        throw new Exception('Không tồn tại mã này');
    }
    $list_category=$dt_xl_post->read_category();
    function print_list($list,$id,$characters,$id_select) {
        $str='';
    	foreach ($list as $location){
    		if ($location['parent'] == $id):
                if($location['type_category']==0){ 
                    $location['type_category']='Tin Tức';
                } else{
                    $location['type_category']='Thông Tin';
                }
    			if ($location['id'] == $id_select){		
    				$str.= '<option selected="selected" value="'.$location['id'].'">'.$characters.$location['category_name'].'&nbsp;&nbsp;&nbsp;('.$location['type_category'].')'.'</option>';
    			} else{
    				$str.= '<option value="'.$location['id'].'">'.$characters.$location['category_name'].'&nbsp;&nbsp;&nbsp;('.$location['type_category'].')'.'</option>';
    			} 
    		    print_list($list, $location['id'], $characters.$characters, $id_select);
    		endif;
        }
        return $str;
    }
   	$dt_smarty->assign('list_category',$list_category);
    $dt_smarty->assign('read_post',$read_post);
	$contenForLayout=$dt_smarty->fetch('posts/posts_update.tpl');
	$dt_smarty->assign('contenForLayout',$contenForLayout);
	$dt_smarty->assign('titleForLayout','Chỉnh sửa bài viết');
	$dt_smarty->display('layout/defaults.tpl');
    $dbh=NULL;
	
} catch(Exception $e){
	$_SESSION['msg']=$e->getMessage();
    $_SESSION['type_msg']='error';
    if(empty($_SERVER['HTTP_REFERER'])){
        header('Location: posts_list.php');
    }else{
        header('Location:'.$_SERVER['HTTP_REFERER']);
    }
    $dbh=NULL;
}
